package com.itheima.reggie.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.crypto.SecureUtil;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Employee;
import com.itheima.reggie.mapper.EmployeeMapper;
import com.itheima.reggie.service.EmployeeService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @author zsk
 * @create 2022-02-14-9:48
 */
@Service
public class EmployeeServiceImpl implements EmployeeService {

    //依赖注入
    @Autowired
    private EmployeeMapper employeeMapper;

    //登陆查询
    @Override
    public ResultInfo login(String username, String password) {

        //调用mapper层查询(根据姓名)
        Employee employee = employeeMapper.findByUserName(username);

        //返回employee对象，进行判断给出具体提示
        if (employee ==null){
            return ResultInfo.error("当前用户不存在");
        }

        //将前台密码加密
        String passwordWithMd5 = new SecureUtil().md5(password);
        //进行密码校验
        if(!StringUtils.equals(passwordWithMd5,employee.getPassword())){
            return ResultInfo.error("密码错误");
        }

        //对状态码进行判断，如果不为一则不允许登录
        if(employee.getStatus() != 1){
            return ResultInfo.error("当前用户处于禁用状态，无法登录");
        }

        //登录成功，返回employee对象
        return ResultInfo.success(employee);
    }

    //查询所有，根据姓名
    @Override
    public List<Employee> findByName(String name) {
        //调用mapper层查询
        return employeeMapper.findByName(name);
    }

    //添加数据
    @Override
    public void save(Employee employee) {
        //补全数据
        employee.setId(IdUtil.getSnowflake(1, 1).nextId());

        //采用md5加密之后
        employee.setPassword(SecureUtil.md5("123456"));
        //状态色号职位启用
        employee.setStatus(1);

        //创建时间和修改时间(默认值为当前时间)
//        employee.setCreateTime(new Date());
//        employee.setUpdateTime(new Date());
//
//        // TODO 创建人和修改人(临时写成1L  后期优化)
//        employee.setCreateUser(1L);
//        employee.setUpdateUser(1L);

        //2. 调用mapper保存
        employeeMapper.save(employee);
    }

    //根据id查询数据
    @Override
    public Employee findById(Long id) {
        //调用mapper层查询
        return employeeMapper.findById(id);
    }

    //修改数据
    @Override
    public void update(Employee employee) {
        //更新修改人与更新时间参数
//        employee.setUpdateTime(new Date());
//        employee.setUpdateUser(1L);

        //调用mapper层修改
        employeeMapper.update(employee);

    }
}
